package com.ds.robot.assistant.job;

import com.google.common.collect.Lists;
import com.ds.robot.assistant.component.MessageSender;
import com.ds.robot.assistant.enums.Env;
import com.ds.robot.assistant.enums.QxUserEnum;
import com.ds.robot.assistant.model.YxPersonBug;
import com.ds.robot.assistant.model.YxProjectBug;
import com.ds.robot.assistant.model.YxReqBug;
import com.ds.robot.assistant.model.YxStatusBug;
import com.ds.robot.assistant.service.HolidayServiceContext;
import com.ds.robot.assistant.service.yunxiao.YunXiaoBase;
import com.ds.robot.assistant.service.yunxiao.YunXiaoBugClient;
import com.ds.robot.assistant.service.yunxiao.YunXiaoRequirementClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;

import static com.ds.robot.assistant.service.yunxiao.YunXiaoBugClient.STATE_ORDER_LIST;

/**
 * 作用：
 *
 * @author WeiShaoying
 * 
 */
@Service
@Slf4j
@SuppressWarnings("SpellCheckingInspection")
public class YunXiaoBugTipJob {

    @Autowired
    private YunXiaoRequirementClient requirementClient;

    @Autowired
    private YunXiaoBugClient bugClient;

    @Autowired
    private HolidayServiceContext holidayServiceContext;

    @Autowired
    private MessageSender messageSender;


    @Scheduled(cron = "0 30 8 * * *")
    // @Scheduled(cron = "0 30 8 * * MON-FRI")
    public void sendBugReportJob() {
        sendBugReport(true);
    }

    @Scheduled(cron = "0 30 18 * * FRI")
    public void sendBugReportJobFriday() {
        sendBugReport(true);
    }

    public void sendBugReport(boolean sendProd) {
        if (sendProd && holidayServiceContext.isRestDay(LocalDate.now().toString())) {
            log.info("今天是休息日，不发缺陷报告");
            return;
        }
        log.info("正常发送缺陷提醒");

        List<YxProjectBug> projectBugList = bugClient.queryProjectBugList();
        if (Objects.isNull(projectBugList)) {
            projectBugList = Lists.newArrayList();
        }
        // log.info(JSON.toJSONString(projectBugList));
        List<YxProjectBug> bugList = projectBugList.stream().sorted(Comparator.comparingInt(YxProjectBug::getBugCount).reversed())
                .map(projectBug -> {
                    List<YxReqBug> reqBugList = projectBug.getReqBugList().stream().sorted(Comparator.comparingInt(YxReqBug::getBugCount).reversed())
                            .map(req -> {
                                List<YxPersonBug> personBugList = req.getPersonBugList().stream().sorted(Comparator.comparingInt(YxPersonBug::getBugCount).reversed())
                                        .map(person -> {
                                            List<YxStatusBug> statusBugList = person.getStatusBugList().stream()
                                                    .sorted(Comparator.comparingInt(statusBug -> STATE_ORDER_LIST.indexOf(statusBug.getStatus())))
                                                    .collect(Collectors.toList());
                                            return new YxPersonBug(person.getPersonName(), person.getBugCount(), statusBugList);
                                        }).collect(Collectors.toList());

                                return new YxReqBug(req.getReqName(), req.getBugCount(), personBugList);
                            }).collect(Collectors.toList());

                    return new YxProjectBug(projectBug.getProjectId(), projectBug.getProjectName(), projectBug.getBugCount(), reqBugList);
                })
                .collect(Collectors.toList());
        // log.info(JSON.toJSONString(bugList));
        String message = null;
        try {
            message = getMessage(bugList);
        } catch (Exception e) {
            log.error("getMessage发生错误", e);
        }
        if (StringUtils.hasText(message)) {
            messageSender.sendMessage(message, Env.TEST,
                    Lists.newArrayList(QxUserEnum.WSY.getId(), QxUserEnum.WJN.getId(), QxUserEnum.WYW.getId(), QxUserEnum.LC.getId(), QxUserEnum.JHP.getId(), QxUserEnum.LMQ.getId(), QxUserEnum.LHM.getId(),
                            QxUserEnum.MH.getId(), QxUserEnum.LYL.getId(), QxUserEnum.WGS.getId()
                    ));
            if (sendProd) {
                messageSender.sendMessage(message, Env.PROD);
            }
        }
    }

    private String getMessage(List<YxProjectBug> list) throws Exception {
        StringBuilder title = new StringBuilder("# [当前尚未解决缺陷跟踪报告]\n");
        if (Objects.isNull(list)) {
            list = Lists.newArrayList();
        }
        int sum = list.stream().mapToInt(YxProjectBug::getBugCount).sum();
        title.append("**缺陷总计：<font color=\"warning\">[").append(sum).append("]</font>** \n\n\n");
        if (sum > 0) {
            StringBuilder content = new StringBuilder();

            for (YxProjectBug projectBug : list) {
                // ## <font color="info">用户端项目[2]</font>
                content.append("## <font color=\"info\">").append(projectBug.getProjectName()).append("[").append(projectBug.getBugCount()).append("]</font>\n");
                // ### 需求:人康直播优化一期[1]
                //         >  邓中建：处理中 <font color="warning">**[1]**</font>

                for (YxReqBug reqBug : projectBug.getReqBugList()) {
                    content.append("### 需求:").append(reqBug.getReqName()).append("[").append(reqBug.getBugCount()).append("]\n");

                    for (YxPersonBug personBug : reqBug.getPersonBugList()) {
                        content.append("   >  ").append(personBug.getPersonName()).append("：");

                        for (YxStatusBug statusBug : personBug.getStatusBugList()) {
                            content.append(statusBug.getStatus()).append(" <font color=\"warning\">**[").append(statusBug.getBugCount()).append("]**</font>，");
                        }
                        if (content.toString().endsWith("，")) {
                            content = new StringBuilder(content.substring(0, content.length() - 1) + "\n");
                        }
                    }
                    //这个不能少，少了会从上到下全部引用
                    content.append("\n");
                }

                String bugUrl = String.format(YunXiaoBase.BUG_FORMART, projectBug.getProjectId());
                // String bugUrl = Optional.ofNullable(projectCache.get(projectBug.getProjectId())).map(ProjectInfoEntity::getBugUrl).orElse(null);
                // if (!StringUtils.hasText(bugUrl)) {
                //     log.warn("========ProjectCache没有命中BugUrl");
                //     bugUrl = BUG_URL_MAP.getOrDefault(projectBug.getProjectId(), "https://devops.aliyun.com/projex/project/889ea8b1980f95b17a579997e1/bug#viewIdentifier=1dedc5afd44979211cad516f");
                // } else {
                //     log.warn("========ProjectCache命中BugUrl");
                // }
                content.append("[查看缺陷](").append(bugUrl).append(")");
                content.append("\n\n\n");
            }
            title.append(content);
        } else {
            title.append("### Good Job !\n");
        }

        title.append("\n <@wjn> <@w> <@liuchen_tqav> <@jianghaipeng_6g1v> <@lanhuimin_mkfr> <@limengqian_ft2b> <@MaHui> <@所有人> \n请悉知~");
        return title.toString();
    }


    // private static <T extends Comparable<T>> List<T> sortBugs(List<T> items) {
    //     return items.stream()
    //             .sorted(Comparator.comparing(T::getBugCount).reversed())
    //             .collect(Collectors.toList());
    // }

    @Scheduled(cron = "0 50 8 * * MON")
    public void sendRequirementReportTip() {
        sendRequirementReport(true);
    }


    public void sendRequirementReport(boolean sendProd) {
        if (sendProd && holidayServiceContext.isRestDay(LocalDate.now().toString())) {
            log.info("今天是休息日，不发需求报告");
            return;
        }
        log.info("正常发需求提醒");
        String message = null;
        try {
            message = requirementClient.queryRequirementMessage();
        } catch (Exception e) {
            log.error("queryRequirementMessage发生错误", e);
        }
        if (StringUtils.hasText(message)) {
            messageSender.sendMessage(message, Env.TEST);
            if (sendProd) {
                messageSender.sendMessage(message, Env.PRODUCT_GROUP);
            }
        }
    }


    public static void main(String[] args) {
        Map<String, Long> map = new HashMap<>();
        map.put("开发完成", 12L);
        map.put("处理中", 18L);
        map.put("待处理", 3L);
        map.put("重新打开", 64L);

        List<String> sortList = Arrays.asList("待处理", "待确认", "处理中", "开发中", "开发完成", "重新打开");

        // 使用流和Collectors来创建一个排序后的LinkedHashMap
        Map<String, Long> sortedMap = map.entrySet().stream()
                .sorted(Comparator.comparingInt(entry -> sortList.indexOf(entry.getKey())))
                .collect(Collectors.toMap(
                        Map.Entry::getKey,
                        Map.Entry::getValue,
                        (existing, replacement) -> existing,
                        LinkedHashMap::new)); // 使用LinkedHashMap保持顺序
        sortedMap.forEach((key, value) -> System.out.println(key + ": " + value));
    }
}
